package corej.course.thread.multiThread;

public class TestProducerConsumer {
    public static void main(String[] args) {
        MyStack ms = new MyStack();
        Thread t1 = new Producer(ms);
        Thread t2 = new Consumer(ms);
        t1.start();
        t2.start();
    }
}

class MyStack {

    char[] data = new char[6];

    int index = 0;

    public synchronized void push(char c) {
        while (index == data.length) {
            try {
                this.notifyAll(); // notify Consumer
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.print(c + " pushed!   ");
        data[index] = c;
        index++;
        // this.notifyAll(); //notify Consumer
        print();
    }

    public synchronized void pop() {
        while (index == 0) {
            try {
                this.notifyAll(); // notify Producer
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        index--;
        System.out.print(data[index] + " poped!   ");
        data[index] = ' ';
        // this.notifyAll(); //notify Producer
        print();
    }

    public void print() {
        for (int i = 0; i < index; i++) {
            System.out.print(data[i] + "  ");
        }
        System.out.println();
    }
}

class Producer extends Thread {
    MyStack ms;

    public Producer(MyStack ms) {
        super();
        this.ms = ms;
    }

    public void run() {
        for (char c = 'A'; c <= 'Z'; c++) {
            ms.push(c);
        }
    }

}

class Consumer extends Thread {
    MyStack ms;

    public Consumer(MyStack ms) {
        super();
        this.ms = ms;
    }

    public void run() {
        for (int i = 1; i <= 26; i++) {
            ms.pop();
        }
    }
}
